/*
 * @Author: wangtao
 * @Date: 2020-07-11 07:16:44
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-08-12 16:46:17
 * @Description: 主入口
 */

import React, { Component } from 'react';
import {
  View,
  StatusBar,
  InteractionManager,
  TextInput,
  Text,
  NativeModules,
  AppState,
  DeviceEventEmitter
} from 'react-native';

import { NavigationActions, StackActions } from 'react-navigation';
import SyncStorage from 'sync-storage';
import { msg, Tip, MessageBox, MessageBoxBig, AsyncStorage } from '@/common';
import api from '@/api';
import baseConfig from './config/baseConfig';
import { uploadImage } from './config';
import * as wechat from './common/wechat';
import { AppContainer } from './router';

let CookieManager = NativeModules.RNCookieManagerIOS;

const { wechatObj, apiObj } = baseConfig;

TextInput.defaultProps = {
  ...TextInput.defaultProps,
  allowFontScaling: false,
  onFocus: () => StatusBar.setBarStyle('dark-content'),
};
Text.defaultProps = { ...Text.defaultProps, allowFontScaling: false };
const defaultFontFamily = {
  color: '#333333',
  ...Platform.select({
    android: { fontFamily: '' },
  }),
};
const oldRender = Text.render;
Text.render = function (...args) {
  const origin = oldRender.call(this, ...args);
  return React.cloneElement(origin, {
    style: [defaultFontFamily, origin.props.style],
  });
};
// 通知客户端当前环境
NativeModules.BridgeManager.initlizationBaseUrlString(apiObj.host);
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // app在前台或者后台 active background
      appState: AppState.currentState,
      // 错误tip的显示状态
      isTipVisible: false,
      // tip的text
      isTipText: '',
      // tip的icon
      isTipIcon: '',

      // 需要主动关闭的弹框
      isSelfTipVisible: false,
      // 需要主动关闭的弹框文本
      isSelfTipVisibleText: '',
      // 需要主动关闭的弹框文本
      isSelfTipVisibleIcon: '',

      // 可交互弹框是否显示start
      isMessageBoxShow: false,
      isMessageBoxTitle: '',
      isMessageBoxText: '',
      isMessageBoxSecText: '',
      isMessageBoxOkText: '',
      isMessageBoxCancelText: '',
      isMessageBoxOkFn: null,
      isMessageBoxCancelFn: null,
      isMessageBoxImgSource: null,
      isHeaderCancel: false,
      isBgClick: true,
      isOkBtnBg: false,
      // 可交互弹框是否显示end

      // 可替换登录框是否显示start
      isMessageBoxBigShow: false,
      isMessageBoxBigText: '',
      isMessageBoxBigOkText: '',
      isMessageBoxBigOkFn: null,
      isMessageBoxBigImgSource: null,
      // 可替换登录框是否显示end

    };
    this.appNetListener = null;
    this.waterCameraHistoryRecords = []; // 获取到的水印相机本地未上传的资源
    this.waterCameraHistoryRecordsTag = []; // 已上传资源
    this.waterCameraFlag = true; // 上传是否结束
  }

  componentDidMount() {
    wechat.registerApp(wechatObj.appid);
    InteractionManager.runAfterInteractions(() => {
      this.initization();
      this._register();
      AppState.addEventListener('change', this._handleAppStateChange);
      this.appNetListener = DeviceEventEmitter.addListener('APP_NET_CONNECT', () => {
        NativeModules.DataModule.getAllWater((res) => {
          console.log('🚀🚀🚀wimi======>>>getAllWater', JSON.parse(res));
          this.waterCameraHistoryRecords = JSON.parse(res);
          if (this.waterCameraFlag) {
            this.waterCameraFlag = false;
            this.waterCameraHistoryRecords.forEach(e => {
              this.uploadWaterImage(e);
            });
          }
        });
      });
    });
  }

  componentWillUnmount() {
    this._unRegister();
    AppState.removeEventListener('change', this._handleAppStateChange);
    this.appNetListener && this.appNetListener.remove();
  }

  render() {
    return (
      <View style={{ flex: 1 }}>
        <StatusBar translucent={false} barStyle='dark-content' />
        <AppContainer
          ref={(obj) => {
            this.nav = obj;
          }}
        />
        <Tip
          modal={false}
          text={this.state.isTipText}
          icon={this.state.isTipIcon}
          visible={this.state.isTipVisible}
          onTipDisappear={this._handleTipDisappear}
        />
        {/* 上面的tip主要用于轻提示，自动会关闭，下面这种是主动关闭 */}
        {this.state.isSelfTipVisible && (
          <Tip
            modal
            time={false}
            visible
            icon={this.state.isSelfTipVisibleIcon}
            text={this.state.isSelfTipVisibleText}
          />
        )}
        {/* 可自定义的弹框，替换LoginTips */}
        {this.state.isMessageBoxBigShow && (
          <MessageBoxBig
            text={this.state.isMessageBoxBigText}
            okText={this.state.isMessageBoxBigOkText}
            okFn={this.state.isMessageBoxBigOkFn}
            imgSource={this.state.isMessageBoxBigImgSource}
          />
        )}
        {/* 可交互的弹框，仿造elementUI的简易实现（正好最近在研究elementUI） */}
        {this.state.isMessageBoxShow && (
          <MessageBox
            title={this.state.isMessageBoxTitle}
            text={this.state.isMessageBoxText}
            secText={this.state.isMessageBoxSecText}
            okText={this.state.isMessageBoxOkText}
            cancelText={this.state.isMessageBoxCancelText}
            okFn={this.state.isMessageBoxOkFn}
            cancelFn={this.state.isMessageBoxCancelFn}
            imgSource={this.state.isMessageBoxImgSource}
            headerCancel={this.state.isHeaderCancel}
            isClickBg={this.state.isBgClick}
            okBtnBg={this.state.isOkBtnBg}
          />
        )}
      </View>
    );
  }

  // 初始化存储（同步AsyncStorage）
  initization = async () => {
    const data = await SyncStorage.init();
    if (__DEV__) {
      console.warn(
        '>>***************AsyncStorage is ready!***********<<',
        data,
      );
    }
    // iOS设置cookie
    if (Platform.OS === 'ios') {
      AsyncStorage.getItem('XMSESSION')
        .then((res) => {
          CookieManager.set(res);
        })
        .catch((err) => {
          console.log('cookie获取异常->', err);
        });
    }
  };

  // app状态改变时的监听
  _handleAppStateChange = nextAppState => {
    if (nextAppState === 'active' && __DEV__) {
      console.log('🚀🚀🚀wimi======>>>当前App切换到了前台', nextAppState);
    }
    if (nextAppState === 'background' && __DEV__) {
      console.log('🚀🚀🚀wimi======>>>当前App切换到了后台', nextAppState);
    }
  };

  // 上传图片
  uploadWaterImage = (dataDic) => {
    let path = dataDic.filePath;
    uploadImage('upload?dirName=waterImages', path).then(res => {
      if (res.success) {
        // 接口
        let param = { lat: dataDic.lat, lgt: dataDic.lng, pictureId: res.data.localId, uploadTime: dataDic.time, address: dataDic.address };
        api.supply.addDriverPictureInfo(param).then(picInfoRes => {
          if (picInfoRes.success) {
            dataDic.status = 'success';
          } else {
            dataDic.status = 'failed';
          }
          this.waterCameraHistoryRecordsTag.push(dataDic);
        }).finally(() => {
          // 如果上传完成把结果告诉原生
          if (this.waterCameraHistoryRecordsTag.length === this.waterCameraHistoryRecords.length) {
            let waterCameraHistoryRecordsTagSuccess = [];
            this.waterCameraHistoryRecordsTag.forEach((item) => {
              if (item.status === 'success') {
                waterCameraHistoryRecordsTagSuccess.push(item);
              }
            });
            if (waterCameraHistoryRecordsTagSuccess.length) {
              this.waterCameraHistoryRecords = [];
              this.waterCameraHistoryRecordsTag = [];
              this.waterCameraFlag = true;
              NativeModules.DataModule.uploadWaterSuccess(JSON.stringify(waterCameraHistoryRecordsTagSuccess));
            }
          }
        });
      } else {
        dataDic.status = 'failed';
        this.waterCameraHistoryRecordsTag.push(dataDic);
      }
    }).catch(() => {
      dataDic.status = 'failed';
      this.waterCameraHistoryRecordsTag.push(dataDic);
    }).finally(() => {
      // 如果上传完成把结果告诉原生
      if (this.waterCameraHistoryRecordsTag.length === this.waterCameraHistoryRecords.length) {
        let waterCameraHistoryRecordsTagSuccess = this.waterCameraHistoryRecordsTag.map((item) => {
          if (item.status === 'success') {
            return item;
          }
        });
        if (waterCameraHistoryRecordsTagSuccess.length) {
          this.waterCameraHistoryRecords = [];
          this.waterCameraHistoryRecordsTag = [];
          this.waterCameraFlag = true;
          NativeModules.DataModule.uploadWaterSuccess(JSON.stringify(waterCameraHistoryRecordsTagSuccess));
        }
      }
    });
  }

  /**
   * 注册的事件
   * @private
   */
  _register = () => {
    msg.on('app:tip', this._handleAppTip); // 弹出tips提示
    msg.on('router: goToNext', this._goToNext); // 下一页
    msg.on('router: back', this._back); // 返回上一页
    msg.on('router: backToTop', this._backToTop); // 返回栈顶
    msg.on('router: backToLast', this._backToLast); // 返回路由末位
    msg.on('router: replace', this._replaceRoute); // 替换栈顶
    msg.on('router: reset', this._resetRoute); // 重置路由栈
    msg.on('router: setParams', this._setParams);
    msg.on('router: refresh', this._refresh); // 刷新当前页(栈顶)
    msg.on('router: refreshRoute', this._refreshRoute); // 刷新指定页面
    msg.on('router: refreshRoutes', this._refreshRoutes); // 刷新指定多个页面
    msg.on('app:selfTip', this._handleSelfTip); // 主动关闭的模态框
    msg.on('app:messageBox', this._handleMessageBox); // 可交互的弹框
    msg.on('app:messageBoxBig', this._handleMessageBoxBig); // 可交互的弹框
  };

  /**
   * 取消注册的事件
   * @private
   */
  _unRegister = () => {
    msg.off('app:tip', this._handleAppTip);
    msg.off('router: goToNext', this._goToNext);
    msg.off('router: back', this._back);
    msg.off('router: backToTop', this._backToTop);
    msg.off('router: backToLast', this._backToLast);
    msg.off('router: replace', this._replaceRoute);
    msg.off('router: reset', this._resetRoute);
    msg.off('router: setParams', this._setParams);
    msg.off('router: refresh', this._refresh);
    msg.off('router: refreshRoute', this._refreshRoute);
    msg.off('router: refreshRoutes', this._refreshRoutes);
    msg.off('app:selfTip', this._handleSelfTip);
    msg.off('app:messageBox', this._handleMessageBox);
    msg.off('app:messageBoxBig', this._handleMessageBoxBig);
  };

  /**
   * 跳转下一路由
   * @param route
   * @private
   */
  _goToNext = (route) => {
    if (__DEV__) {
      console.log('goToNext.....', route);
    }
    const { routeName, ...others } = route;

    const navigateAction = NavigationActions.navigate({
      routeName,
      params: others,
    });
    this.nav.dispatch(navigateAction);
  };

  /**
   * 返回
   * @param route
   * @private
   */
  _back = (route) => {
    if (__DEV__) {
      console.log('back.....', route);
    }
    let backAction = NavigationActions.back();
    if (route) {
      const { key } = route;
      if (__DEV__) {
        console.log('key...', key);
      }
      backAction = NavigationActions.back({
        key,
      });
    }
    if (__DEV__) {
      console.log('backAction...', backAction);
    }
    this.nav.dispatch(backAction);
  };

  /**
   * 返回路由首位
   * @private
   */
  _backToTop = () => {
    const { routes } = this.nav.state.nav;
    if (__DEV__) {
      console.log('backToTop...', routes);
    }
    this.nav.dispatch({
      type: 'backToTop',
    });
  };

  /**
   * 返回路由末位
   * @private
   */
  _backToLast = () => {
    if (__DEV__) {
      console.log('backToLast----->');
    }
    const { routes } = this.nav.state.nav;
    this._back(routes[routes.length - 1]);
  };

  /**
   * 替换路由
   * @param route
   * @private
   */
  _replaceRoute = (route) => {
    if (__DEV__) {
      console.log('replace router---->', route);
    }
    this.nav.dispatch({
      type: 'replace',
      ...route,
    });
  };

  /**
   * 重置路由
   * @param route
   * @private
   */
  _resetRoute = (route) => {
    if (__DEV__) {
      console.log('replace router---->', route);
    }
    const resetAction = StackActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({ routeName: route.routeName }), // 要跳转到的页面名字
      ],
    });

    this.nav.dispatch(resetAction);
  };

  /**
   * 刷新当前页(栈顶)
   * @private
   */
  _refresh = () => {
    this.nav.dispatch({ type: 'refresh' });
  };

  /**
   * 刷新指定页面
   * @private
   */
  _refreshRoute = (route) => {
    this.nav.dispatch({
      type: 'refreshRoute',
      routeName: route.routeName,
    });
  };

  /**
   * 刷新指定多个页面
   * @private
   */
  _refreshRoutes = (route) => {
    this.nav.dispatch({
      type: 'refreshRoutes',
      routeNames: route.routeNames,
    });
  };

  /**
   * 设置参数
   * @param params
   * @private
   */
  _setParams = (params) => {
    const { routes } = this.nav.state.nav;
    if (__DEV__) {
      console.log('params...', params);
      console.log('backToTop...', routes);
    }

    let { key } = routes[routes.length - 1];

    // 取最后一个路由
    const route = routes[routes.length - 1];
    // 如果是Tab，需要把params设置到对应的子路由上
    if (route.routeName === 'Tab') {
      const subIndex = route.index;
      // route.routes[subIndex].params = params
      key = route.routes[subIndex].key;
    }

    if (__DEV__) {
      console.log('key...', key);
    }
    const setParamsAction = NavigationActions.setParams({
      params,
      key,
    });
    this.nav.dispatch(setParamsAction);
  };

  /**
   * 处理Tip
   */
  _handleAppTip = ({ text, icon, time = 2000 }) => {
    this.setState({
      isTipVisible: true,
      isTipText: text,
      isTipIcon: icon,
      time,
    });
  };

  /**
   * 恢复Tip的原始状态
   */
  _handleTipDisappear = () => {
    this.setState({
      isTipVisible: false,
      isTipText: '',
      isTipIcon: '',
    });
  };

  // 主动关闭弹框
  _handleSelfTip = ({ isVisible, text = '正在支付中...', icon = 'loading' }) => {
    this.setState({
      isSelfTipVisible: isVisible,
      isSelfTipVisibleText: text,
      isSelfTipVisibleIcon: icon,
    });
  };

  // 可交互弹框
  _handleMessageBox = ({
    isVisible,
    title,
    text,
    secText,
    okText,
    cancelText,
    okFn,
    cancelFn,
    imgSource,
    headerCancel,
    okBtnBg,
    isClickBg,
  }) => {
    this.setState({
      isMessageBoxShow: isVisible,
      isMessageBoxTitle: title,
      isMessageBoxText: text,
      isMessageBoxSecText: secText,
      isMessageBoxOkText: okText,
      isMessageBoxCancelText: cancelText,
      isMessageBoxOkFn: okFn,
      isMessageBoxCancelFn: cancelFn,
      isMessageBoxImgSource: imgSource,
      isHeaderCancel: headerCancel,
      isBgClick: isClickBg,
      isOkBtnBg: okBtnBg,
    });
  };

  // 可交互弹框
  _handleMessageBoxBig = ({ isVisible, text, okText, okFn, imgSource }) => {
    this.setState({
      isMessageBoxBigShow: isVisible,
      isMessageBoxBigText: text,
      isMessageBoxBigOkText: okText,
      isMessageBoxBigOkFn: okFn,
      isMessageBoxBigImgSource: imgSource,
    });
  };
}
